package com.yeyks.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yeyks.constant.ConfigKey;
import com.yeyks.dal.dao.CashOutOrderMapper;
import com.yeyks.dal.domain.CashOutOrder;
import com.yeyks.dal.domain.UserBill;
import com.yeyks.dal.domain.UserInfo;
import com.yeyks.dto.AccountOverviewDTO;
import com.yeyks.dto.UserAccountOverviewDTO;
import com.yeyks.exception.ServiceException;
import com.yeyks.service.CashOutOrderService;
import com.yeyks.service.ConfigService;
import com.yeyks.service.UserAccountOverviewService;
import com.yeyks.util.DateUtils;
import com.yeyks.util.IdWorkerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author fuchangshuai
 * @date 2019/4/28 0028
 */
@Slf4j
@Service
public class CashOutOrderServiceImpl implements CashOutOrderService {

    @Autowired
    private CashOutOrderMapper cashOutOrderMapper;
    @Autowired
    private UserAccountOverviewService overviewService;
    @Autowired
    private ConfigService configService;

    /**
     * 获取指定用户最新的提现记录
     *
     * @param userId
     * @return
     */
    @Override
    public CashOutOrder getNewestCashOutOrder(Integer userId) {
        return cashOutOrderMapper.getNewestCashOutOrder(userId);
    }

    /**
     * 我的佣金页面
     *
     * @param userInfo
     * @return
     */
    @Override
    public AccountOverviewDTO info(UserInfo userInfo) {
        AccountOverviewDTO overviewDTO = new AccountOverviewDTO();
        overviewDTO.setFlag(false);
        overviewDTO.setRemainAmount(0);
        overviewDTO.setStatus(null);
        UserAccountOverviewDTO info = overviewService.info(userInfo);
        if (info == null) {
            return overviewDTO;
        }
        overviewDTO.setRemainAmount(info.getRemainAmount());
        //首先判断是否有提现中的记录，有的话直接status = 1(提现中)，flag = false，
        // 没有记录才判断今天是否已提现
        CashOutOrder cash = getNewestCashOutOrder(userInfo.getId());
        if (cash == null) {
            overviewDTO.setFlag(true);
            return overviewDTO;
        }
        if (cash.getStatus() != null
                && cash.getStatus().equals(CashOutOrder.Status.pre_check.value())) {
            overviewDTO.setStatus(cash.getStatus());
            return overviewDTO;
        }
        Date orderDate = cash.getGmtCreate();
        if (orderDate == null) {
            overviewDTO.setFlag(true);
            return overviewDTO;
        }
        Date newBeginDate = DateUtils.dayBegin(0);
        //当前已提现过
        if (DateUtils.dateCompareDate(orderDate, newBeginDate)) {
            overviewDTO.setFlag(false);
        } else {
            overviewDTO.setFlag(true);
        }
        return overviewDTO;
    }

    /**
     * 用户提现(银行卡)
     *
     * @param userInfo
     * @param amount
     * @return
     */
    @Override
    @Transactional
    public Boolean extract(UserInfo userInfo, Integer amount) {

        AccountOverviewDTO info = info(userInfo);
        if (info.getStatus() != null && info.getStatus().equals(1)) {
            throw new ServiceException("您有提现中的订单");
        }
        if (!info.getFlag()) {
            throw new ServiceException("您今天已提现过了");
        }
        //提现，用户余额减少
        if (overviewService.descAmount(amount, userInfo.getId(), UserBill.Type.WITHDRAW.value(), UserBill.Type.WITHDRAW.desc())) {
            CashOutOrder cashOutOrder = getCashOutOrder(userInfo, amount);
            return cashOutOrderMapper.insert(cashOutOrder) == 1;
        }
        return false;
    }

    private CashOutOrder getCashOutOrder(UserInfo userInfo, Integer amount) {
        CashOutOrder cashOutOrder = new CashOutOrder();
        cashOutOrder.setAmount(amount);
        cashOutOrder.setAuditId(null);//审核人
        cashOutOrder.setAuditTime(null);//审核时间
        cashOutOrder.setDeleteFlag(0);//0；未删除  1：已删除
        cashOutOrder.setOrderNo(IdWorkerUtil.nextStrId());//订单号
        cashOutOrder.setStatus(1);//1待审核，2审核通过，3 审核未通过，4 失败
        cashOutOrder.setUserId(userInfo.getId());
        cashOutOrder.setPhone(userInfo.getPhone());
        return cashOutOrder;
    }

    /**
     * 提现常见问题
     *
     * @return
     */
    @Override
    public Object problem() {
        try {
            String value = configService.getValue(ConfigKey.EXTRACT_PROBLEM);
            return JSONObject.parseObject(value);

        } catch (Exception e) {
            log.error("提现常见问题异常{}", e.getLocalizedMessage());
            e.printStackTrace();
            return getDefault();
        }
    }

    private Map<String, Object> getDefault() {
        Map<String, Object> jsonObject = new HashMap<>();
        List<String> extractRuleList = Lists.newArrayList();
        extractRuleList.add("1. 佣金累计满100元可提现");
        extractRuleList.add("2. 提现到账预计48小时内到账，如超过48小时未到账您可联系客服询问详情");
        extractRuleList.add("3. 佣金提现每天只能申请提现一次");
        extractRuleList.add("4. 佣金提现需要绑定银行卡");
        jsonObject.put("extractRule", extractRuleList);
        List<String> bankBindList = Lists.newArrayList();
        bankBindList.add("1. 只能绑定一张银行卡,且只支持绑定16-19位银行卡号的国内借记卡");
        bankBindList.add("2. 如何绑定：点击去绑定按钮，输入正确的持卡人、卡号、银行名称、开户支行信息点击确定即可完成绑定");
        bankBindList.add("3. 如何修改：点击修改银行卡按钮，输入正确的持卡人、卡号、银行名称、开户支行信息点击确定即可修改银行卡信息");
        jsonObject.put("bankBindRule", bankBindList);
        List<String> warmPromptList = Lists.newArrayList();
        warmPromptList.add("1. 请务必输入正确的银行卡信息，否则将可能出现提现失败等情况");
        warmPromptList.add("2. 若有其它疑问请联系客服：400-8263595客服时间：9：00  -  17:00");
        jsonObject.put("warmPrompt", warmPromptList);
        return jsonObject;
    }
}
